package com.woniu.config;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.woniu.dao.StudentDao;
import com.woniu.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
//加密后的敏感字段还能进行模糊查询吗？可以这样做！
@Component
public class PassWordDeal {

    @Autowired
    private StudentDao studentDao;

    @Transactional
    public Student register(Student student) {
        String phoneNumber = student.getPhoneNumber();
        //加密入库
        String phoneNumberEncrypt = encrypt(phoneNumber);
        student.setPhoneNumber(phoneNumberEncrypt);
        studentDao.insert(student);

        //分词加密
        String phoneKeywords = this.phoneKeywords(phoneNumber);

        //存入分词密文映射表 sys_person_phone_encrypt
        studentDao.insertPhoneKeyworkds(student.getId(), phoneKeywords);
        return student;
    }

    private String phoneKeywords(String phone) {
        String keywords = this.keywords(phone, 4);
        System.out.println(keywords.length());
        return keywords;
    }

    //分词组合加密
    private String keywords(String word, int len) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < word.length(); i++) {
            int start = i;
            int end = i + len;
            String sub1 = word.substring(start, end);
            sb.append(this.encrypt(sub1));
            if (end == word.length()) {
                break;
            }
        }
        return sb.toString();
    }

    public String encrypt(String val) {
        //这里特别注意一下，对称加密是根据密钥进行加密和解密的，加密和解密的密钥是相同的，一旦泄漏，就无秘密可言，
        //“fanfu-csdn”就是我自定义的密钥，这里仅作演示使用，实际业务中，这个密钥要以安全的方式存储；
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue(), "fanfu-csdn".getBytes()).getEncoded();
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.DES, key);
        String encryptValue = aes.encryptBase64(val);
        return encryptValue;
    }

    public String decrypt(String val) {
        //这里特别注意一下，对称加密是根据密钥进行加密和解密的，加密和解密的密钥是相同的，一旦泄漏，就无秘密可言，
        //“fanfu-csdn”就是我自定义的密钥，这里仅作演示使用，实际业务中，这个密钥要以安全的方式存储；
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue(), "fanfu-csdn".getBytes()).getEncoded();
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.DES, key);
        String encryptValue = aes.decryptStr(val);
        return encryptValue;
    }


}
